<script>
import {
  TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
} from '@/config'
import EnergyTableMixin from '@/components/quarterly-account-table/energy-table-mixin'
import ArrowSelectMixin from '@/components/quarterly-account-table/arrow-select-mixin'
import ContextMenuMixin from '@/components/quarterly-account-table/context-menu-mixin'
import {
  loadProductEnergyConsumption,
} from '@/api/enterpriseQuarterlyReport'
import { uuid } from '@/utils'

export default {
  name: 'table-of-comprehensive-energy-consumption-per-unit-product',
  mixins: [EnergyTableMixin, ContextMenuMixin, ArrowSelectMixin],
  created () {
    this.loadList = loadProductEnergyConsumption
  },
  data () {
    return {
      calculationKeys: [
        'indexValue',
        'indexValueOne',
        'childValueOne',
        'parentValueOne',
      ],
      // 表序号
      seriesNo: '表1-3',
    }
  },
  computed: {
    calc () {
      const lists = this.lists
      const keys = this.calculationKeys

      // 指标值=子项值÷母项值*单位换算系数
      const index = (a, b, s) => {
        const n = +(((+a) / (+b) * (+s || 1)).toFixed(2))
        return Number.isFinite(n) ? n : ''
      }
      return keys.reduce((acc, vv) => {
        // 本年度指标是计算而来
        // 上年度是带出来的数据
        acc[vv] = lists.map((v, i) => {
          v = v.data
          const child = v.find(x => x.key === 'childValue') || {}
          const parent = v.find(x => x.key === 'parentValue') || {}
          const sss = v.find(x => x.key === 'unitConversionFactor') || {}
          const target = v.find(x => x.key === vv) || {}
          return vv === 'indexValue'
            ? index(child.value, parent.value, sss.value)
            : target.value
        })
        return acc
      }, {})
    },
  },
  methods: {
    transfer (lists) {
      const keys = this.calculationKeys
      const props = this.flattenColumns.map(v => v.prop)
      return lists.map((v) => {
        return {
          uuid: uuid(),
          informant: {
            personInCharge: v.personInCharge,
            informer: v.informer,
            telephone: v.telephone,
            fillInDate: v.fillInDate,
          },
          data: props.map((vv) => {
            let editable = true
            let calculable
            if (keys.includes(vv)) {
              editable = false
              calculable = true
            }
            if (this.readonly) {
              editable = false
            }
            return {
              key: vv,
              value: String(v[vv] || ''),
              editable,
              calculable,
            }
          })
        }
      })
    },
    // 创建空行
    createAEmptyRow () {
      const item = (this.flattenColumns || []).reduce((acc, v) => {
        acc[v.prop] = ''
        return acc
      }, {})
      return this.transfer([item])[0].data
    },

    getCalc (row, prop, value) {
      const calc = this.calc
      return calc[prop] ? calc[prop][row] : value
    },
    // 初始化表数据
    initLists (params) {
      // 查询企业填报的数据
      if (this.loadList) {
        params = params || {
          [TABLE_FIELD_YEAR]: this.year,
          [TABLE_FIELD_QUARTER]: this.quarter,
          tenantId: this.enterpriseId
        }
        return this.loadList(params).then(async res => {
          if (res.code === 200) {
            const data = res.data || []
            this.lists = this.transfer(data)
            if (!this.fromGovernmentSide) {
              // 补足企业端不足行的数据
              const l = this.lists.length
              // 行数不需太多，2行足够
              this._initLists(l, 2)
            }

            this.$nextTick(() => {
              this.initInputIndex()
            })
          }
        }).catch(() => {
          console.log('reject')
          this._initLists(0)
          this.$nextTick(() => {
            this.initInputIndex()
          })
        })
      }
    },
  },
}
</script>

<template>
  <div class="bg-white height-100 quarterly-account-table position-relative overflow-hidden">
    <slot name="title" :title="title" :series-no="seriesNo">
      <h2 class="table-title">
        {{title}}
      </h2>
    </slot>
    <div class="report-table-head">
      <table class="report-table">
        <table-head :columns="columns" :show-line-number="showLineNumber"></table-head>
      </table>
    </div>
    <el-scrollbar :style="{height: 'calc(100% - 130px)'}" wrap-style="overflow-x: hidden;">
      <table class="report-table">
        <tbody ref="tbody">
        <tr v-for="(item, i) in lists" :key="item.uuid">
          <th v-if="showLineNumber" class="readonly width-40px line-number">{{i + 1}}</th>
          <td
            v-for="(d, index) in item.data" :key="item.uuid + index"
            :class="{
              'is-calculable': d.calculable
            }"
          >
            <div v-if="!d.editable" class="span-cell">
              {{d.calculable ? calc[d.key][i] : d.value}}
            </div>
            <div v-else class="input-cell">
              <input
                type="text" v-model="d.value"
                @click="clickHandler($event, i)" @contextmenu="onContextmenu"
              >
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <report-person ref="reportPerson" :informer="informant"></report-person>
      <div v-if="tableDescription" class="fill-description">
        <template>
          <!-- <p>说明：</p>
          <p>1．本表甲栏按照附件3《工业企业单位产品能耗指标填报目录》填写。</p>
          <p>2．国家（地区）限额按照国家或地区能耗限额标准填写，如果没有能耗限额标准可不填写。</p>
          <p>3．对影响能耗指标变化的主要原因给予说明，字数在100个汉字以内。</p> -->

          <el-input type="textarea" class="width-100 table-description" :value="tableDescription" readonly autosize></el-input>
        </template>
      </div>
    </el-scrollbar>
    <transition name="el-fade-in">
      <ul v-if="visible" :style="{left:left+'px', top: top + 'px'}" class="contextmenu">
        <li style="color:var(--danger-color);" @click="delRow">删除当前行</li>
        <li class="divider"></li>
        <li @click="prependRow">在上方插入一行</li>
        <li @click="appendRow">在下方插入一行</li>
      </ul>
    </transition>
  </div>
</template>
